<template>
  <div>
    <el-breadcrumb class="mb-4" separator=">">
      <el-breadcrumb-item :to="{ path: '/expert/home' }">询标结果</el-breadcrumb-item>
      <el-breadcrumb-item>询标详情</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 询标信息卡片 -->
    <el-card class="mb-6">
      <div slot="header" class="card-header">
        <div class="header-left">
          <i class="el-icon-document"></i>
          <span class="header-title">询标信息</span>
        </div>
        <el-tag v-if="countdownVisible" type="primary" class="countdown-tag">
          <i class="el-icon-time"></i>
          {{ countdownText }}
        </el-tag>
      </div>
      <div class="card-content">
        <el-row :gutter="20">
          <el-col
            :span="8"
            v-for="(bidder, index) in bidders"
            :key="index"
          >
            <el-card class="bidder-card">
              <div class="bidder-info">
                <div class="bidder-name">
                  <i class="el-icon-office-building"></i>
                  <span>{{ bidder.name }}</span>
                </div>
                <div class="bidder-contact">
                  <i class="el-icon-user"></i>
                  <span>{{ bidder.contact }}</span>
                  <span class="divider">/</span>
                  <span>{{ bidder.phone }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-postcard"></i>
                项目编号
              </div>
              <div class="info-value">
                {{projectNo}}
              </div>
            </div>
          </el-col>
         
          <el-col :span="24">
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-paperclip"></i>
                附件内容
              </div>
              <div class="attachment-content">
                <div v-if="attachmentList.length > 0" class="attachment-list">
                  <el-tag
                    v-for="file in attachmentList"
                    :key="file.Id"
                    type="primary"
                    class="attachment-tag"
                    @click="downloadFilePage(file)"
                  >
                    <i :class="getFileIcon(file.DisplayName)"></i>
                    {{ file.DisplayName }}
                    <i class="el-icon-download"></i>
                  </el-tag>
                </div>
                <div v-else class="no-attachment">
                  暂无附件
                </div>
              </div>
            </div>
          </el-col>

        </el-row>
      </div>
    </el-card>

    <!-- 询标结果卡片 -->

    <el-card class="mb-6">
      <div slot="header" class="card-header">
        <div class="header-left">
          <i class="el-icon-check"></i>
          <span class="header-title">询标结果</span>
          <el-tag type="info" class="inquiry-no-tag">
            <i class="el-icon-document"></i>
            {{InquiryNo}}
          </el-tag>
        </div>
        <!-- <el-button 
          type="primary" 
          :loading="downloading"
          :disabled="!hasAttachments"
          @click="downloadAllFiles"
        >
          <i class="el-icon-download"></i>
          下载全部附件
        </el-button> -->
      </div>

      <div class="card-content">
        <!-- <el-col :span="24">
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-edit-outline"></i>
                回复内容
              </div>
              <div class="info-value">
                {{replyContent}}
              </div>
            </div>
          </el-col> -->
         <el-col :span="24">
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-paperclip"></i>
                回答附件内容
              </div>
              <div class="attachment-content">
                <div v-if="attachmentAnswerList.length > 0" class="attachment-list">
                  <el-tag
                    v-for="file in attachmentAnswerList"
                    :key="file.Id"
                    type="primary"
                    class="attachment-tag"
                    @click="downloadFilePage(file)"
                  >
                    <i :class="getFileIcon(file.DisplayName)"></i>
                    {{ file.DisplayName }}
                    <i class="el-icon-download"></i>
                  </el-tag>
                </div>
                <div v-else class="no-attachment">
                  暂无附件
                </div>
              </div>
            </div>
          </el-col>
        <!-- 投标单位列表卡片形式，暂时不用 -->
        <!--<el-row :gutter="20">
          <el-col
            :span="24"
            v-for="(bidder, index) in inquiryData.bidders"
            :key="index"
          >
            <el-card class="bidder-detail-card">
              <el-alert type="info" :closable="false">
                <div class="bidder-header">
                  <i class="el-icon-office-building"></i>
                  <span>{{ bidder.name }}</span>
                </div>
                <div class="bidder-contact">
                  <i class="el-icon-user"></i>
                  <span>{{ bidder.contact }}</span>
                  <span class="divider">/</span>
                  <span>{{ bidder.phone }}</span>
                </div>
              </el-alert>
              <div class="bidder-content">
                <div class="content-section">
                  <div class="info-label">
                    <i class="el-icon-document"></i>
                    询标内容
                  </div>
                  <div class="info-value">
                    {{ inquiryData.content }}
                  </div>
                  <div class="info-label">
                    <i class="el-icon-paperclip"></i>
                    附件内容
                  </div>
                  <div class="attachment-content">
                    <div class="attachment-list">
                      <el-tag
                        v-for="(file, index) in inquiryData.attachments"
                        :key="index"
                        type="primary"
                        class="attachment-tag"
                        @click="downloadFile(file)"
                      >
                        <i :class="getFileIcon(file.type)"></i>
                        {{ file.name }}
                        <i class="el-icon-download"></i>
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row> -->
      </div>
    </el-card>
  </div>
</template>

<script>
import { GetInquiryReplyRecordById, GetInquiryRecordById } from "@/api/InquiryRecord";
import { downloadFile as apiDownloadFile } from "@/api/api.js";

export default {
  name: 'ExpertInquiryDetail',
  data() {
    return {
      // 基本数据
      attachmentList: [],
      attachmentAnswerList: [],
      InquiryNo: '',
      inquiryContent: '',
      replyContent: '',
      inquiryId: '',
      projectNo: '',
      projectName: '',
      deadlineTime: '',
      loading: false,
      Id: '',

      // 展示数据（页面上有使用）
      bidders: [],

      // 倒计时
      deadline: null,
      countdownText: '',
      countdownVisible: false,
      countdownTimer: null,

      // 示例数据（如果后续需要可使用）
      inquiryData: {
        id: 1,
        projectNumber: "PRJ20240516001",
        content: "这是一个示例询标内容，请专家进行评审。需要评估投标单位的资质、技术方案、报价等方面。",
        deadline: "2025-05-16 16:00:00",
        status: "pending",
        bidders: [
          { id: 1, name: "示例投标单位1", contact: "张三", phone: "13800138001" },
          { id: 2, name: "示例投标单位2", contact: "李四", phone: "13800138002" },
          { id: 3, name: "示例投标单位3", contact: "王五", phone: "13800138003" },
        ],
        attachments: [
          { name: "附件1.pdf", type: "pdf" },
          { name: "附件2.docx", type: "docx" },
        ],
      }
    }
  },
  computed: {
    hasAttachments() {
      return (this.attachmentList?.length > 0 || this.attachmentAnswerList?.length > 0);
    },
    // 如需使用状态颜色可打开
    // statusColor() {
    //   const now = new Date();
    //   const dl = new Date(this.inquiryData.deadline);
    //   if (now > dl) return "error";
    //   if (this.inquiryData.status === "replied") return "success";
    //   return "primary";
    // }
  },
  methods: {
    pad(n) {
      return String(n).padStart(2, '0');
    },
    parseDeadline(val) {
      if (!val) return null;
      let t = Date.parse(val);
      if (!isNaN(t)) return t;
      t = Date.parse(String(val).replace(/-/g, '/')); // 兼容 yyyy-MM-dd HH:mm:ss
      return isNaN(t) ? null : t;
    },
    updateCountdown() {
      const end = this.parseDeadline(this.deadline);
      if (!end) {
        this.countdownVisible = false;
        return;
      }
      const diff = end - Date.now();
      if (diff <= 0) {
        this.countdownVisible = false;
        if (this.countdownTimer) {
          clearInterval(this.countdownTimer);
          this.countdownTimer = null;
        }
        return;
      }
      const totalSec = Math.floor(diff / 1000);
      const hours = Math.floor(totalSec / 3600);
      const minutes = Math.floor((totalSec % 3600) / 60);
      const seconds = totalSec % 60;
      this.countdownText = `${this.pad(hours)}:${this.pad(minutes)}:${this.pad(seconds)}`;
      this.countdownVisible = true;
    },

    // 获取文件图标（支持通过文件名识别扩展名）
    getFileIcon(nameOrExt) {
      const ext = String(nameOrExt || '')
        .split('.')
        .pop()
        .toLowerCase();
      const map = {
        pdf: "el-icon-document",
        doc: "el-icon-document",
        docx: "el-icon-document",
        xls: "el-icon-document",
        xlsx: "el-icon-document",
        ppt: "el-icon-document",
        pptx: "el-icon-document",
        jpg: "el-icon-picture",
        jpeg: "el-icon-picture",
        png: "el-icon-picture",
      };
      return map[ext] || "el-icon-document";
    },

    // 下载全部附件（如需启用，取消模板中对应按钮的注释）
    async downloadAllFiles() {
      if (!this.hasAttachments) {
        this.$message.error('没有可下载的附件');
        return;
      }
      this.downloading = true;
      try {
        const allFiles = [
          ...(this.attachmentAnswerList || [])
        ];
        for (const file of allFiles) {
          await new Promise(resolve => setTimeout(resolve, 500));
          try {
            const link = document.createElement('a');
            link.href = file.FileAllPath;
            link.download = file.DisplayName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          } catch (err) {
            console.error(`下载文件 ${file.DisplayName} 失败:`, err);
          }
        }
        this.$message.success('所有文件开始下载');
      } catch (error) {
        console.error('批量下载文件失败:', error);
        this.$message.error('下载失败，请稍后重试');
      } finally {
        this.downloading = false;
      }
    },

    // 单个文件下载
    async downloadFilePage(file) {
      try {
        const params = {
          path: file.FilePath,
          name: file.DisplayName
        };
        await apiDownloadFile(params);
      } catch (error) {
        console.error('下载文件失败:', error);
      }
    },

    // 返回列表
    goBack() {
      this.$router.push("/expert/inquiries");
    },

    // 拉取详情（保留原有结构）
    async fetchInquiryDetails() {
      this.loading = true;
      try {
        const inquiry = await GetInquiryRecordById(this.Id);
        if (inquiry && inquiry.IsSuccess && inquiry.Data) {
          this.projectNo = inquiry.Data.ProjectNo || this.projectNo;
          this.projectName = inquiry.Data.ProjectName || this.projectName;
          this.deadlineTime = inquiry.Data.DeadlineTime || this.deadlineTime;
          this.attachmentList = inquiry.Data.Attachement || [];
        }
      } catch (error) {
        console.error('获取询标详情失败:', error);
        this.$message.error('获取询标详情失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    }
  },
  async mounted() {
    this.Id = this.$route.query.Id || '';
    // 根据 ID 调用接口获取详情
    if (this.Id) {
      const inquiryReply = await GetInquiryReplyRecordById(this.Id);
      this.InquiryNo = inquiryReply?.Data?.InquiryNo || '';
      this.inquiryContent = inquiryReply?.Data?.InquiryContent || '';
      this.replyContent = inquiryReply?.Data?.ReplyContent || '';

      // 拉取原始询标
      if (inquiryReply && inquiryReply.Data) {
        const origin = await GetInquiryRecordById(inquiryReply.Data.InquiryRecordId);
        this.attachmentList = origin?.Data?.Attachement || [];
        this.projectNo = origin?.Data?.ProjectNo || this.projectNo;
        this.attachmentAnswerList = inquiryReply?.Data?.Attachement || [];
      }

      // 倒计时
      this.deadline = inquiryReply?.Data?.DeadlineTime || null;
      this.updateCountdown();
      if (!this.countdownTimer) {
        this.countdownTimer = setInterval(this.updateCountdown, 1000);
      }
    }
    // 继续执行原有详情拉取
    this.fetchInquiryDetails();
  },
  beforeDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
      this.countdownTimer = null;
    }
  }
}
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}

.mb-6 {
  margin-bottom: 24px;
}

.el-card {
  transition: all 0.3s ease;
  margin-bottom: 24px;
}

.el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.countdown-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

.inquiry-no-tag {
  margin-left: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-content {
  padding-top: 16px;
}

.bidder-card {
  margin-bottom: 12px;
  border: 1px solid #EBEEF5;
}

.bidder-info {
  padding: 16px;
}

.bidder-name {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-weight: 500;
  color: #303133;
}

.bidder-contact {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.divider {
  color: #C0C4CC;
  margin: 0 8px;
}

.info-item {
  padding: 16px;
  border-radius: 8px;
  background-color: #F5F7FA;
  margin-bottom: 16px;
}

.info-label {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #909399;
  font-size: 14px;
}

.info-value {
  line-height: 1.6;
  color: #303133;
  font-weight: 500;
}

.attachment-content {
  margin-top: 8px;
}

.attachment-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.attachment-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
}

.attachment-tag:hover {
  background-color: #ECF5FF;
  border-color: #409EFF;
}

.no-attachment {
  color: #909399;
  font-style: italic;
}

.el-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .header-left {
    flex-wrap: wrap;
  }
  
  .inquiry-no-tag {
    margin-left: 0;
    margin-top: 8px;
  }
  
  .attachment-list {
    flex-direction: column;
  }
  
  .attachment-tag {
    justify-content: space-between;
  }
}
</style>
